package com.ovo.dailypayaccount.controller;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.ovo.dailypayaccount.entity.UserInfo;
import com.ovo.dailypayaccount.service.BaseUserService;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private BaseUserService userService;

	@RequestMapping("/showUser")
	@ResponseBody
	public UserInfo toIndex(HttpServletRequest request, Model model) {
		int userId = Integer.parseInt(request.getParameter("id"));
		UserInfo user = this.userService.getUserById(userId);
		return user;
	}
	
	/**
	 * 修改密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/changePassword")
	public ModelMap changePassword(HttpServletRequest request, HttpServletResponse response) {
		ModelMap result = new ModelMap();
		String lastPwd = request.getParameter("lastPwd");//旧密码
		String newpwd = request.getParameter("newpwd");//新密码
		Cookie[]cookies = request.getCookies();
		UserInfo user = null;
		String userId = null;
		if(cookies!=null) {	
			for(Cookie cookie:cookies) {
				if(cookie.getName().equals("userId")) {
					userId = cookie.getValue();
				}
			}
			if(userId!=null) {
				user = userService.getUserById(Integer.valueOf(userId));
				if(null!=user&&user.getPassword().equals(lastPwd)) {
					user.setId(Integer.valueOf(userId));
					user.setPassword(newpwd);
					user.setCreateTime(new Date());
					int rs = userService.updateByPrimaryKeySelective(user);
					if(rs==1) {//更新成功
						result.put("userName", user.getName());
						result.put("status", "1");
						result.put("msg", "密码修改成功，请重新登录!");
						return result;
					}
				}else {
					result.put("status", "0");
					result.put("msg", "旧密码不正确，请重新输入!");
				}
				
			}
		}
		return result;
	}
}
